<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="sku名称" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入sku名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:skuInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:skuInfo:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="skuId" align="center" prop="skuId" />
      <el-table-column label="spuId" align="center" prop="spuId" />
      <el-table-column label="sku名称" align="center" prop="skuName" />
      <el-table-column label="sku介绍描述" align="center" prop="skuDesc" />
      <el-table-column label="默认图片" align="center" prop="skuDefaultImg">
        <template #default="scope">
          <image-preview
            :src="scope.row.skuDefaultImg"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="skuTitle" />
      <el-table-column label="副标题" align="center" prop="skuSubTitle" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="销量" align="center" prop="saleCount" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <div class="table-action">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleImages(scope.row)"
              v-hasPermi="['product:skuInfo:edit']"
              >图集</el-button
            >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['product:skuInfo:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleAttr(scope.row)"
              v-hasPermi="['product:spuInfo:edit']"
              >属性</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:skuInfo:remove']"
              >删除</el-button
            >
            <el-dropdown>
              <el-button link type="primary"
                >更多<el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    ><router-link to="/ware/sku"
                      >库存信息</router-link
                    ></el-dropdown-item
                  >
                  <el-dropdown-item
                    ><router-link to="/marketing/bounds"
                      >积分信息</router-link
                    ></el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改sku信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="sku名称" prop="skuName">
          <el-input v-model="form.skuName" placeholder="请输入sku名称" />
        </el-form-item>
        <el-form-item label="spu名称" prop="spuId">
          <el-select v-model="form.spuId" placeholder="请选择spu">
            <el-option
              v-for="item in spuList"
              :key="item.spuId"
              :label="item.spuName"
              :value="item.spuId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="skuDesc">
          <el-input
            type="textarea"
            v-model="form.skuDesc"
            placeholder="请输入sku介绍描述"
          />
        </el-form-item>
        <!-- <el-form-item label="默认图片" prop="skuDefaultImg">
          <image-upload v-model="form.skuDefaultImg"></image-upload>
        </el-form-item> -->
        <el-form-item label="标题" prop="skuTitle">
          <el-input v-model="form.skuTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="skuSubTitle">
          <el-input v-model="form.skuSubTitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            placeholder="请输入价格"
            controls-position="right"
          />
        </el-form-item>
        <!-- <el-form-item label="销量" prop="saleCount">
          <el-input v-model="form.saleCount" placeholder="请输入销量" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改sku attr信息 -->
    <el-dialog :title="title" v-model="attrOpen" width="800px" append-to-body>
      <el-table :data="attrList" border stripe>
        <el-table-column
          label="属性名称"
          prop="attrName"
          width="80"
        ></el-table-column>
        <el-table-column label="属性值" prop="valueSelect">
          <template #default="scope">
            <el-radio-group
              v-if="scope.row.valueSelect.length > 1"
              v-model="attrForm[scope.$index].attrValue"
            >
              <el-radio
                v-for="(item, index) in scope.row.valueSelect"
                :key="index"
                :label="item"
              >
                {{ item }}
              </el-radio>
            </el-radio-group>
            <el-input
              v-model="attrForm[scope.$index].attrValue"
              style="width: 200px"
              v-else
            >
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div
        style="
          margin-top: 10px;
          display: flex;
          flex-direction: flex-end;
          width: 100%;
        "
      >
        <el-button type="primary" @click="submitAttrForm">确定</el-button>
        <el-button @click="attrOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改sku images信息 -->
    <el-dialog :title="title" v-model="imageOpen" width="800px" append-to-body>
      <el-popover
        placement="right"
        :width="500"
        :visible="isAddImg"
        trigger="click"
      >
        <template #reference>
          <el-button
            size="small"
            icon="Upload"
            type="primary"
            @click="handleAddImg"
            style="margin-bottom: 10px"
            >添加图片</el-button
          >
        </template>
        <el-form ref="imgFormRef" :model="imgForm" :rules="imgRules">
          <el-form-item label="排序" prop="imgSort">
            <el-input-number
              v-model="imgForm.imgSort"
              controls-position="right"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="图片" prop="imgUrl">
            <image-upload
              v-model="imgForm.imgUrl"
              :limit="1"
              :width="60"
              :height="60"
            ></image-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitImgForm">确定</el-button>
            <el-button @click="isAddImg = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-popover>
      <el-table :data="imageList" border stripe>
        <el-table-column label="序号" prop="id" width="80"></el-table-column>
        <el-table-column label="图片" align="center" prop="skuDefaultImg">
          <template #default="scope">
            <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          prop="imgSort"
          width="80"
        ></el-table-column>
        <el-table-column label="默认" prop="defaultImg" width="80">
          <template #default="scope">
            <el-icon
              color="#1aa684"
              size="20px"
              v-show="scope.row.defaultImg == 1"
            >
              <CircleCheckFilled />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              link
              size="small"
              type="primary"
              icon="Edit"
              @click="handleUpdateImg(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              size="small"
              type="danger"
              icon="Delete"
              @click="handleDelImg(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  listSkuInfo,
  getSkuInfo,
  delSkuInfo,
  addSkuInfo,
  updateSkuInfo,
  updateSku2Attr,
} from "@/api/mall/server/product/maintain/sku";
import { listSpuInfo } from "@/api/mall/server/product/maintain/spu";
import {
  listSaleAttrValueBySku,
  listSaleAttrBySku,
} from "@/api/mall/server/product/attribute";
import {
  listSkuImagesBySkuId,
  addSkuImages,
  updateSkuImages,
  delSkuImages,
} from "@/api/mall/server/product/maintain/skuImages";
import { ref, watch } from "vue";
const { proxy } = getCurrentInstance();
const total = ref(0);
const loading = ref(false);
const list = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const open = ref(false);
const formRef = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {},
});
const { queryParams, form, rules } = toRefs(data);
// 列表查询
const getList = async () => {
  loading.value = true;
  const res = await listSkuInfo(queryParams.value);
  list.value = res.rows;
  loading.value = false;
};

// 图片管理
const isAddImg = ref(false);
const imgForm = ref({});
const imgRules = reactive({
  imgUrl: {
    required: true,
    message: "图片不能为空",
  },
  imgSort: {
    required: true,
    message: "排序不能为空",
  },
});
watch(
  () => isAddImg.value,
  (val) => {
    if (!val) {
      imgForm.value.id = undefined;
      imgForm.value.imgUrl = undefined;
      imgForm.value.imgSort = undefined;
    }
  }
);
const imgFormRef = ref();
const handleAddImg = () => {
  // imgForm.value.id = undefined;
  // imgForm.value.imgUrl = undefined;
  // imgForm.value.imgSort = undefined;
  isAddImg.value = true;
};
const handleUpdateImg = async (row) => {
  imgForm.value = JSON.parse(JSON.stringify(row));
  isAddImg.value = true;
};
const handleDelImg = async (row) => {
  proxy.$modal.confirm("确定删除SPU图片集？").then(async () => {
    let skuId = row.skuId;
    const res = await delSkuImages(row.id);
    proxy.$message.success("删除成功");
    handleImages({ skuId: skuId });
  });
};
const submitImgForm = () => {
  console.log(imgForm.value);
  imgFormRef.value.validate((valid) => {
    if (valid) {
      if (imgForm.value.id != undefined) {
        updateSkuImages(imgForm.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          handleImages(imgForm.value);
          isAddImg.value = false;
        });
      } else {
        addSkuImages(imgForm.value).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          handleImages(imgForm.value);
          isAddImg.value = false;
        });
      }
    }
  });
};
// 取消
const cancel = () => {
  open.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    skuId: undefined,
    spuId: undefined,
    skuName: undefined,
    skuDesc: undefined,
    catalogId: undefined,
    brandId: undefined,
    skuDefaultImg: undefined,
    skuTitle: undefined,
    skuSubTitle: undefined,
    price: undefined,
    saleCount: undefined,
  };
};
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 表单重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.skuId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
// 添加弹窗
const handleAdd = (row) => {
  reset();
  open.value = true;
  title.value = "添加商品SKU信息";
};
// 修改操作
const handleUpdate = async (row) => {
  reset();
  const skuId = row.skuId || ids.value;
  const res = await getSkuInfo(skuId);
  form.value = res.data;
  open.value = true;
  title.value = "修改商品SKU信息";
};
// 表单提交
const submitForm = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.spuId != undefined) {
        updateSkuInfo(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSkuInfo(form.value).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 删除
const handleDelete = (row) => {
  const ids = row.skuId || ids.value;
  proxy.$modal
    .confirm(`是否确认删除编号位${ids}的数据项?`)
    .then((res) => {
      return delSkuInfo(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
// 查询spu信息
const spuList = ref([]);
const getSpuList = async () => {
  const res = await listSpuInfo();
  spuList.value = res.rows;
};

// 编辑属性
const attrOpen = ref(false);
const attrList = ref([]);
const handleAttr = async (row) => {
  title.value = "修改商品SKU属性";
  console.log("scope", row);
  Promise.all([getSaleAttrValue(row.skuId), getSaleAttr(row.skuId)]).then(
    (res) => {
      attrOpen.value = true;
    }
  );
};

const attrForm = ref([]);
const submitAttrForm = async () => {
  console.log("saleAttrs", attrForm.value);
  await updateSku2Attr(attrForm.value).then((res) => {
    proxy.$modal.msgSuccess("修改成功");
    attrOpen.value = false;
    getList();
  });
};
// 获取saleAttrValue
const getSaleAttrValue = async (skuId) => {
  const res = await listSaleAttrValueBySku(skuId);
  attrForm.value = res.data;
  console.log("attrForm", attrForm.value);
};
// 获取baseAttr
const getSaleAttr = async (skuId) => {
  const res = await listSaleAttrBySku(skuId);
  // 修改valueSelect
  attrList.value = res.data;
  attrList.value.map((item) => {
    return (item.valueSelect = item.valueSelect.split(","));
  });
  console.log("attrList", attrList.value);
};

// 图片
const imageOpen = ref(false);
const imageList = ref([]);
const handleImages = async (row) => {
  title.value = "修改商品介绍图集";
  console.log("scope", row);
  const res = await listSkuImagesBySkuId(row.skuId);
  imageList.value = res.data;
  imageOpen.value = true;
};

getList();
getSpuList();
</script>

<style lang="scss" scoped>
.table-action {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-button {
    margin-left: 0;
    margin-top: 2px;
  }
}
</style>
